/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wii.elpro.web.action;

import com.wii.elpro.dao.UserDAOInterface;
import com.wii.elpro.dao.hb.CabangDAOImpl;
import com.wii.elpro.dao.hb.DepartemenDAOImpl;
import com.wii.elpro.dao.hb.UserDAOImpl;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.UserUpdateForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author hp02
 */
public class UserUpdateAction extends Action {

    public UserUpdateAction() {
    }

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User users = (User)sess.getAttribute("userSession");       
        if(users==null){
            return mapping.findForward("gagalLogin");            
        }  
        String forward;
        UserUpdateForm f = (UserUpdateForm) form;
        UserDAOInterface dao = new UserDAOImpl();
        User user = new User();
        user.setAlamat(f.getAlamat());
        user.setCabang(new CabangDAOImpl().getCabang(f.getIdCabang()));
        user.setDepartemen(new DepartemenDAOImpl().getDepartemen(f.getIdDepartemen()));
        user.setEmail(f.getEmail());
        user.setNama(f.getNama());
        user.setPassword(f.getPassword());
        user.setId(f.getId());
        user.setUsername(f.getUsername());
//        PASSWORD IS NOT CHANGE IF PASSFIELD IS EMPTY
//        if (!updateForm.getPassword().isEmpty()) {
//            user.setPassword(updateForm.getPassword());
//        }
//        if(!updateForm.getPassword().equals(updateForm.getPasswordRetype())){
//            
//        }

        // CHANGE USER INFORMATION IN SESSION        
        if(sess.getAttribute("userSession")!=null) {
            User uSession = (User) sess.getAttribute("userSession");
            if (uSession.getUsername().equalsIgnoreCase(user.getUsername())) {
                uSession = user;
                sess.setAttribute("userSession", uSession);
            }
        }
        user.setTelp(f.getTelp());
        try {
            dao.update(user);
            forward = "success";
        } catch (Exception e) {
            forward = "fail";
            e.printStackTrace();
        }
        return mapping.findForward(forward);
    }
}
